<-- back

Valid Parentheses

Link

Just used the stack data structure and popped something out when a closing symbol appeared. If I didn't get what was expected, I returned false.

Full Solution in Java:

public class Solution { public boolean isValid(String s) { Stack< Character> st = new Stack< Character>(); for(int i=0; i< s.length(); i++){ char x= s.charAt(i); if(x==')'){ if(st.empty()){ return false; } char c = st.pop(); if(c!='('){ return false; } } else if(s.charAt(i)=='}'){ if(st.empty()){ return false; } char c = st.pop(); if(c!='{'){ return false; } } else if(s.charAt(i)==']'){ if(st.empty()){ return false; } char c = st.pop(); if(c!='['){ return false; } } else{ st.push(s.charAt(i)); } } if(!st.empty()){ return false; } return true; } }